<template>
  <div class="container">
    <div class="form-container">
      <h1>车辆信息</h1>
      <el-form :model="form" ref="topForm" :rules="rules" label-width="120px">
        <!-- 车牌号表单 -->
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="form.licensePlate" type="text"></el-input>
        </el-form-item>
        <!-- 到场时间表单 -->
        <el-form-item label="到场时间" prop="arrivalTime">
          <el-date-picker v-model="form.arrivalTime" type="datetime"></el-date-picker>
        </el-form-item>
        <!-- 净重表单 -->
        <el-form-item label="净重" prop="netWeight">
          <el-input v-model="form.netWeight" type="number" step="10"></el-input>
        </el-form-item>
        <!-- 皮重表单 -->
        <el-form-item label="皮重">
          <el-input v-model="form.skinWeight" type="number" step="10"></el-input>
        </el-form-item>
        <el-form-item>
          <!-- 生成按钮和重置按钮 -->
          <el-button type="primary" @click="generateForm">生成</el-button>
          <el-button type="warning" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 提示模块 -->
    <div class="notice">
      <p v-if="showNotice">{{ noticeMessage }}</p>
    </div>

    <div class="form-container">
      <h1>地磅单</h1>
      <!-- 地磅单信息表单 -->
      <el-form :model="resultForm" label-width="120px">
        <el-form-item label="磅单号">
          <!-- 磅单号显示为纯文本 -->
          <b>{{ resultForm.billNumber }}</b>
        </el-form-item>
        <el-form-item label="过毛时间">
          <!-- 过毛时间显示为纯文本 -->
          <b>{{ resultForm.hairTime }}</b>
        </el-form-item>
        <el-form-item label="过皮时间">
          <!-- 过皮时间显示为纯文本 -->
          <b>{{ resultForm.skinTime }}</b>
        </el-form-item>
        <el-form-item label="毛重">
          <!-- 毛重显示为加粗纯文本 -->
          <b>{{ formatInteger(resultForm.grossWeight) }}</b>
        </el-form-item>
        <el-form-item label="皮重">
          <!-- 皮重显示为加粗纯文本 -->
          <b>{{ formatInteger(resultForm.skinWeight) }}</b>
        </el-form-item>
        <el-form-item label="净重">
          <!-- 净重显示为加粗纯文本 -->
          <b>{{ formatInteger(resultForm.netWeight) }}</b>
        </el-form-item>
      </el-form>
    </div>

    <div class="placeholder"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      lastNetWeight: '', // 用于存储上次的净重
      lastSkinWeight: '', // 用于存储上次的皮重
      netWeightChanged: false, // 标记净重是否发生变化
      showNotice: false, // 控制提示模块的显示状态
      noticeMessage: '', // 提示信息
      form: {
        licensePlate: this.getStoredValue('licensePlate') || '', // 获取本地存储中的车牌号
        arrivalTime: new Date(), // 默认选择当前时间
        netWeight: this.getStoredValue('netWeight') || '', // 获取本地存储中的净重
        skinWeight: this.getStoredValue('skinWeight') || '', // 获取本地存储中的皮重
      },
      resultForm: {
        billNumber: '',
        skinTime: '',
        hairTime: '',
        grossWeight: '',
        netWeight: '',
        skinWeight: '',
      },
      rules: {
        licensePlate: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { validator: this.validateLicensePlate, trigger: 'blur' },
        ],
        arrivalTime: [
          { required: true, message: '请选择到场时间', trigger: 'change' },
        ],
        netWeight: [
          { required: true, message: '请输入净重', trigger: 'blur' },
          { validator: this.validateNetWeight, trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    generateRandomSeconds() {
      // 生成随机秒数，范围在01到59之间
      return (Math.floor(Math.random() * 59) + 1).toString().padStart(2, '0');
    },

    // 生成随机分钟，范围在min到max之间
    generateRandomMinutes(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    },
    generateForm() {
      this.$refs.topForm.validate((valid) => {
        if (valid) {
          this.handleFormSubmission();
        } else {
          this.$message.error('表单验证失败，请检查输入');
        }
      });
    },
    handleFormSubmission() {
      const { licensePlate, arrivalTime, skinWeight } = this.form;

      // 获取用户选择的到场时间
      const selectedArrivalTime = new Date(arrivalTime);
      const today = new Date(); // 当前日期

      // 将当前日期的时间部分设置为零时零分零秒
      today.setHours(0, 0, 0, 0);

      // 计算日期差异，以确定提示信息
      const dateDiff =
        Math.abs(selectedArrivalTime - today) / (1000 * 60 * 60 * 24); // 将毫秒差异转换为天数

      if (dateDiff > 1 && dateDiff <= 2) {
        // 如果日期差异大于 1 天且小于等于 2 天，即选择的日期为明天或后天
        this.showNotice = true;
        this.noticeMessage = '到场日期不是今天，请注意及时更改到场日期。';
      } else {
        this.showNotice = false; // 隐藏提示
        this.noticeMessage = '';
      }

      const netWeight = parseFloat(this.form.netWeight); // 用户输入的净重
      if (this.lastNetWeight === netWeight) {
        // 如果净重没有变化，则显示提示信息
        this.$message.warning('净重未更改');
        this.netWeightChanged = false; // 设置标记为 false
      } else {
        this.lastNetWeight = netWeight;
        this.netWeightChanged = true; // 设置标记为 true
      }
      // 保存车牌号、净重和皮重到本地存储
      this.saveToStorage('licensePlate', licensePlate);
      this.saveToStorage('netWeight', netWeight.toString());

      const finalSkinWeight = this.calculateSkinWeight(skinWeight);
      this.saveToStorage('skinWeight', finalSkinWeight.toString());

      const grossWeight = Math.floor(finalSkinWeight + netWeight);

      // 获取当前时间
      const now = new Date();
      const grossTime = new Date(
        selectedArrivalTime.getTime() -
          this.generateRandomMinutes(55, 68) * 60 * 1000 -
          this.generateRandomSeconds() * 1000
      );
      const skinTime = new Date(
        grossTime.getTime() -
          this.generateRandomMinutes(17, 23) * 60 * 1000 -
          this.generateRandomSeconds() * 1000
      );

      const billNumber = this.generateBillNumber();

      this.resultForm = {
        billNumber: billNumber,
        skinTime: this.formatDate(skinTime),
        hairTime: this.formatDate(grossTime),
        grossWeight: grossWeight.toFixed(2),
        netWeight: netWeight.toFixed(2),
        skinWeight: finalSkinWeight.toFixed(2),
      };
    },
    calculateSkinWeight(skinWeight) {
      if (skinWeight) {
        return parseFloat(skinWeight);
      } else {
        const minSkinWeight = 16550; // 皮重的最小值
        const maxSkinWeight = 16750; // 皮重的最大值
        const randomSkinWeight =
          Math.floor(Math.random() * (maxSkinWeight - minSkinWeight + 1)) +
          minSkinWeight;
        return Math.ceil(randomSkinWeight / 10) * 10; // 确保是10的倍数
      }
    },
    getStoredValue(key) {
      return localStorage.getItem(key);
    },
    saveToStorage(key, value) {
      localStorage.setItem(key, value);
    },
    resetForm() {
      localStorage.removeItem('licensePlate');
      localStorage.removeItem('netWeight');
      localStorage.removeItem('skinWeight');
      this.form = {
        licensePlate: '',
        arrivalTime: new Date(),
        netWeight: '',
        skinWeight: '',
      };
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    generateBillNumber() {
      const now = new Date(this.form.arrivalTime);
      const hour = now.getHours();
      let A = 1;

      if (hour >= 7 && hour < 9) {
        A = 3;
      } else if (hour >= 9 && hour < 12) {
        A = 5;
      } else if (hour >= 13 && hour < 15) {
        A = 6;
      } else if (hour >= 15 && hour < 17) {
        A = 7;
      }

      const B = Array.from({ length: 3 }, () => Math.floor(Math.random() * 10));
      B.push(Math.floor(Math.random() * 9) + 1);

      return `A1230810${A}${B.join('')}`;
    },
    formatInteger(value) {
      if (Number.isInteger(value)) {
        return value.toString(); // 如果是整数，直接返回字符串形式
      } else {
        return Math.round(value).toString(); // 如果是浮点数，四舍五入后返回字符串形式
      }
    },
  },
};
</script>

<style scoped>
* {
  box-sizing: border-box;
}
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 24px; /* 添加整体内边距，适应PC端 */

  /* 使用margin将内容居中 */
  margin: 0 auto;
  max-width: 1200px; /* 限制内容最大宽度 */
}

.form-container {
  width: 45%;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 24px;

  /* 使用margin将内容居中 */
  margin: 0 auto;

  /* 添加内边距，适应PC端 */
  padding: 20px;
}

h1 {
  font-size: 20px;
  margin-bottom: 20px;
}

.placeholder {
  height: 60px;
}

/* 添加媒体查询，以适应小屏幕（iPhone 6/7/8） */
@media screen and (max-width: 800px) {
  .container {
    padding: 16px; /* 缩小内边距，适应移动端 */
  }

  .form-container {
    width: 100%; /* 适应小屏幕宽度 */

    /* 添加内边距，适应移动端 */
    padding: 10px;
  }

  h1 {
    font-size: 18px; /* 减小标题字号 */
    margin-bottom: 12px; /* 缩小标题下边距 */
  }
}
.notice {
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: red;
  font-weight: 700;
}
</style>